package com.soloyogame.anitoys.my.web.controller.front.coupon;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.soloyogame.anitoys.db.commond.Coupon;
import com.soloyogame.anitoys.db.commond.Account;
import com.soloyogame.anitoys.db.commond.CartInfo;
import com.soloyogame.anitoys.db.commond.Product;
import com.soloyogame.anitoys.db.page.PagerModel;
import com.soloyogame.anitoys.my.web.controller.front.orders.OrderAction;
import com.soloyogame.anitoys.my.web.controller.front.util.LoginUserHolder;
import com.soloyogame.anitoys.my.web.controller.front.util.RequestHolder;
import com.soloyogame.anitoys.service.CouponService;
import com.soloyogame.anitoys.service.HelpService;
import com.soloyogame.anitoys.service.ProductService;
import com.soloyogame.anitoys.util.cache.RedisCacheProvider;
import org.springframework.web.bind.annotation.ResponseBody;


/*
 * 用户优惠券管理
 * @author kuangyong 20151204
 */
@Controller("frontCouponAction")
@RequestMapping("/coupon/")
public class CouponAction
{
	
	@Autowired
	private CouponService couponService;
	@Autowired
	private RedisCacheProvider redisCacheProvider; 
	@Autowired
	private ProductService productService;
	@Autowired
    private HelpService helpService;
	
	private static final String toLogin = "/account/login";//转到登陆界面,forword方式 地址不变
	private static final String page_couponReceList = "/account/couponReceive";
	private static final String page_couponList = "/account/coupon";
	private static final String page_couponDueList = "/account/couponDue";
	
	/**
	 * 跳转到我的优惠券
	 * update 2015-12-05 kuangy 修改按优惠券status状态查询优惠券
	 * status：当为"" 或者null的时候查询的是未过期的优惠券
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("coupons")
	public String coupons(HttpServletRequest request,ModelMap model) throws Exception
	{
		Logger logger = LoggerFactory.getLogger(OrderAction.class);
		//获取当前登录用户
		Account acc = LoginUserHolder.getLoginAccount();
		if (acc == null || StringUtils.isBlank(acc.getAccount())) 
		{
			return toLogin;
		}
		
		List<Product> productList = new ArrayList<Product>();
		if (acc == null || StringUtils.isBlank(acc.getAccount())) {
			return toLogin;
		}
		CartInfo cartInfo = null;
		if(acc==null){
			cartInfo = (CartInfo) redisCacheProvider.get("myCart");
		} else {
			cartInfo = (CartInfo) redisCacheProvider.get("user_"+acc.getId()+"Cart");
		}
		if(cartInfo!=null)
		{
			productList = cartInfo.getProductList();
		} 
		else 
		{
			cartInfo = new CartInfo();
		}
		int productCount=productService.selectProductCount();
		
		model.addAttribute("cartInfo", cartInfo);
		model.addAttribute("productCount", productCount);
		model.addAttribute("productList", productList);
		
		int offset = 0;//分页偏移量
        if (request.getParameter("pager.offset") != null) 
        {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        if (offset < 0)
        	offset = 0;
                
		//获取优惠券状态(0所有，1到期)
		//String status = RequestHolder.getRequest().getParameter("status");
		//因下面对status进行赋值了，但查询完成后该字段需要返回给前台，因此另作定义存值
		//String status1 = status;
		//用来对前台的指向标签定义
        String status = "";
		String style = "20px";
		String usestatus = request.getParameter("usestatus");
		logger.debug("按优惠券状态筛选参数status -->:"+status);
		
		//定义查询实体
		Coupon coupon = new Coupon();
//		coupon.setAccount(acc.getAccount());
		coupon.setAccount(acc.getAccountId());
		coupon.setStatus(status);
		coupon.setOffset(offset);	
		coupon.setPageSize(6);
		
		//查询结果page
		PagerModel pager =  this.couponService.selectFrontPageList(coupon);
		pager.setPageSize(6);
		pager.setPagerSize((pager.getTotal() + pager.getPageSize() - 1)
                / pager.getPageSize());		
		pager.setPagerUrl("coupons");
		
		model.addAttribute("pager", pager);
		model.addAttribute("style", style);
		return page_couponList;
	}
	
	
	/**
	 * 我的到期优惠券
	 * update 2015-12-05 kuangy 修改按优惠券status状态查询优惠券
	 * status :1 得到的是到期的优惠券
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("couponsDue")
	public String couponsDue(HttpServletRequest request,ModelMap model) throws Exception
	{
		Logger logger = LoggerFactory.getLogger(OrderAction.class);
		//获取当前登录用户
		Account acc = LoginUserHolder.getLoginAccount();
		if (acc == null || StringUtils.isBlank(acc.getAccount())) 
		{
			return toLogin;
		}
		List<Product> productList = new ArrayList<Product>();
		if (acc == null || StringUtils.isBlank(acc.getAccount())) 
		{
			return toLogin;
		}
		CartInfo cartInfo = null;
		if(acc==null)
		{
			cartInfo = (CartInfo) redisCacheProvider.get("myCart");
		}
		else
		{
			cartInfo = (CartInfo) redisCacheProvider.get("user_"+acc.getId()+"Cart");
		}
		if(cartInfo!=null)
		{
			productList = cartInfo.getProductList();
		} 
		else 
		{
			cartInfo = new CartInfo();
		}
		int productCount=productService.selectProductCount();
		
		model.addAttribute("cartInfo", cartInfo);
		model.addAttribute("productCount", productCount);
		model.addAttribute("productList", productList);	
		
		int offset = 0;//分页偏移量
        if (request.getParameter("pager.offset") != null) 
        {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        if (offset < 0)
        	offset = 0;
                
		//获取优惠券状态(0所有，1到期)
		//String status = RequestHolder.getRequest().getParameter("status");
		//因下面对status进行赋值了，但查询完成后该字段需要返回给前台，因此另作定义存值
		//String status1 = status;
		//用来对前台的指向标签定义
        String status = "notNull";
		String style = "280px";
		logger.debug("按优惠券状态筛选参数status -->:"+status);
//		if(!StringUtils.isBlank(status)){
//			//我的优惠券
//			if("0".equals(status)){
//				status = "";
//				style = "20px";
//			}
//			//到期优惠券
//			else if("1".equals(status)){
//				status = " and b.endTime < ";
//				style = "280px";
//			}
//		}
		
		//获取用户和优惠券状态
//		paramMap.put("account", acc.getAccount());
//		paramMap.put("status", status);
//		logger.debug(paramMap.get("status")+"--status--------------------");
		//定义查询实体
		Coupon coupon = new Coupon();
//		coupon.setAccount(acc.getAccount());
		coupon.setAccount(acc.getId());
		coupon.setStatus(status);
		coupon.setOffset(offset);	
		coupon.setPageSize(6);
		
		//查询结果page
		PagerModel pager =  this.couponService.selectFrontPageList(coupon);	
		pager.setPageSize(6);
		pager.setPagerSize((pager.getTotal() + pager.getPageSize() - 1)
                / pager.getPageSize());		
		pager.setPagerUrl("couponsDue");
		
		model.addAttribute("pager", pager);
//		model.addAttribute("status", status1);
		model.addAttribute("style", style);
		return page_couponDueList;
	}
	
	

	/**
	 * 查询可领取的优惠券
	 * update 2015-12-05 kuangy
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("couponReceive")
	public String couponReceive(HttpServletRequest request,ModelMap model) throws Exception
	{
		//获取当前登录用户
		Account acc = LoginUserHolder.getLoginAccount();
		if (acc == null || StringUtils.isBlank(acc.getAccount())) 
		{
			return toLogin;
		}
		List<Product> productList = new ArrayList<Product>();
		/*if (acc == null || StringUtils.isBlank(acc.getAccount())) 
		{
			return toLogin;
		}*/
		CartInfo cartInfo = null;
		if(acc==null){
			cartInfo = (CartInfo) redisCacheProvider.get("myCart");
		} else {
			cartInfo = (CartInfo) redisCacheProvider.get("user_"+acc.getId()+"Cart");
		}
		if(cartInfo!=null){
			productList = cartInfo.getProductList();
		} else {
			cartInfo = new CartInfo();
		}
		int productCount = productService.selectProductCount();
		
		model.addAttribute("cartInfo", cartInfo);
		model.addAttribute("productCount", productCount);
		model.addAttribute("productList", productList);	
		
		int offset = 0;//分页偏移量
        if (request.getParameter("pager.offset") != null) {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        if (offset < 0)
        	offset = 0;

		//定义查询实体
		Coupon coupon = new Coupon();
		coupon.setAccount(acc.getId());		
		coupon.setOffset(offset);
		coupon.setPageSize(6);
		//查询结果page
		PagerModel pager =  this.couponService.selectCouponByReceive(coupon);
		pager.setPageSize(6);
		pager.setPagerSize((pager.getTotal() + pager.getPageSize() - 1)
                / pager.getPageSize());
		pager.setPagerUrl("couponReceive");
		model.addAttribute("pager", pager);
		
		return page_couponReceList;
	}
	
	
	/*
	 * 领取优惠券
	 * @author kuangyong 2015-12-08
	 * 
	 */
	@RequestMapping("receiveCoupon")
	@ResponseBody
	public String receiveCoupon(ModelMap model) throws Exception
	{
		// 获取用户登录ID，并判断用户是否登录，若没登录，需返回登录
		Account acc = LoginUserHolder.getLoginAccount();
		if (acc == null || StringUtils.isBlank(acc.getAccount())) 
		{
			return toLogin;
		}
		
		Coupon coupon = new Coupon();
		//获取优惠券编号和自增编号
		String couponSn = RequestHolder.getRequest().getParameter("couponSn");
		String couponId = RequestHolder.getRequest().getParameter("couponId");
		String couponType = RequestHolder.getRequest().getParameter("couponType");
		String endTime = RequestHolder.getRequest().getParameter("endTime");

		coupon.setCouponSn(couponSn);

		//订单编号，领取优惠券时该字段置为空
		coupon.setOrderId(null);
		//优惠券使用状态，领取优惠券时该字段置为1，即未使用
		coupon.setStatus("1");
		//使用时间，领取优惠券时该字段置为空
		coupon.setUseTime(null);
		//优惠券自增编号
		coupon.setCouponId(couponId);
		//优惠券编号
		coupon.setCouponSn(couponSn);
		//优惠券类型
		coupon.setCouponType(Integer.valueOf(couponType));
		//到期日期
		coupon.setExpireTime(endTime);
//		coupon.setUserId(acc.getAccount());
		coupon.setUserId(acc.getAccountId());
		//将用户选择领取的优惠券插入至用户优惠券表T_ACCOUNT_COUPON表
		int isNo = this.couponService.insertCoupon(coupon);

		if(isNo==0) {
			return "0";
		} else {
			return "1";
		}
	}
}
